import { memo, useCallback, useEffect, useRef, useState } from 'react'
import AMap from '@/views/CompanyDetail/components/Amap/AMap.tsx'
import MapIcon1 from '@/assets/AmapImg/mapIcon1.png'
import './SeaMap.css'

const SpaceMap = ({ companyList }) => {
  const activeValue = '投资公司'
  const [cityList, setCityList] = useState([
    {
      label: '全国',
      adcode: 100000,
      zoom: 3.14,
      centroid: [104.113164, 37.570667]
    }
  ])

  const AMapTool = useRef(null)

  const handleCityTabsClick = (item) => {
    setCityList(cityList.slice(0, cityList.indexOf(item) + 1))
    renderDistrictArea(item.adcode, districtExplorerRefs.current)
  }

  const [mapRef, setMapRef] = useState(null)

  const districtExplorerRefs = useRef(null)

  // 创建ui组件库+ui组件库实例
  const createDistrictExplorer = useCallback(async (mapInstance: any) => {
    if (districtExplorerRefs.current) {
      return
    }
    return new Promise((resolve) => {
      // 初始化ui组件库
      window.AMapUI.load(['ui/geo/DistrictExplorer'], (DistrictExplorer: any) => {
        districtExplorerRefs.current = new DistrictExplorer({
          eventSupport: true,
          map: mapInstance
        })

        resolve(true)
      })
    })
  }, [])

  // 将区域数据渲染在地图上初始化区域数据
  const renderAreaNode = useCallback(
    (districtExplorer, areaNode) => {
      //清除已有的绘制内容
      if (districtExplorer) {
        districtExplorer.clearFeaturePolygons()
      }

      //绘制子级区划
      const isCountry = areaNode.adcode === 100000
      districtExplorer.renderSubFeatures(areaNode, function () {
        return {
          cursor: 'pointer',
          bubble: true,
          strokeColor: isCountry ? null : '#0779FF', // 线颜色
          strokeOpacity: isCountry ? 0 : '0.4', // 线透明度
          strokeWeight: isCountry ? 0 : '1', // 线宽
          fillColor: isCountry ? null : '#0779FF', //填充色
          fillOpacity: isCountry ? 0 : '0.35' //填充透明度
        }
      })

      //绘制父级区划，仅用黑色描边
      districtExplorer.renderParentFeature(areaNode, {
        cursor: 'pointer',
        bubble: true,
        strokeColor: null, // 线颜色
        fillColor: null,
        strokeWeight: null // 线宽
      })

      //更新地图视野以适合区划面

      mapRef.setFitView(districtExplorer.getAllFeaturePolygons())
    },
    [mapRef]
  )

  // 渲染区域
  const renderDistrictArea = useCallback(
    async (adcode: number, districtExplorerType: any) => {
      const areaNode = await loadAreaNode(adcode, districtExplorerType)
      districtExplorerType.setAreaNodesForLocating([areaNode])
      await renderAreaNode(districtExplorerType, areaNode)
    },
    [renderAreaNode]
  )

  const option = useCallback((AMap, callback) => {
    callback(async (resMap) => {
      AMapTool.current = AMap
      resMap.setMapStyle('amap://styles/cb3fa971cc1c1d7ad3714d4e42eed3e1')
      setMapRef(resMap)
    })

    return {
      options: {
        zooms: [3.95, 16],
        center: [120.858852, 37.739311],
        showIndoorMap: false,
        isHotspot: false,
        viewMode: '3D',
        resizeEnable: true
      }
    }
  }, [])

  useEffect(() => {
    if (!mapRef) return
    createDistrictExplorer(mapRef).then(() => {
      //加载区域节点
      renderDistrictArea(100000, districtExplorerRefs.current)
      // ui实例的操作
      districtExplorerRefs.current.on('featureClick', async (_, feature: any) => {
        const { center, adcode, level, name: label } = feature.properties

        if (level !== 'district') {
          renderDistrictArea(adcode, districtExplorerRefs.current)
          setCityList((prevState) => [...prevState, { label, adcode }])
        } else {
          mapRef.setCenter(center)
        }
      })
    })
  }, [createDistrictExplorer, mapRef, renderDistrictArea])

  // 地图初始化

  //加载区域坐标数据
  function loadAreaNode(adcode: number, districtExplorerType: any): Promise<any> {
    return new Promise((resolve, reject) => {
      districtExplorerType.loadAreaNode(adcode, (error: any, areaNode: any) => {
        if (error) {
          return reject(error)
        }
        resolve(areaNode)
      })
    })
  }

  const createParkMaker = (data, image, iconConfig = {}, markerConfig = {}) => {
    const [lng, lat] = data.lngLat.split(',')
    const icon = new AMapTool.current.Icon({
      image,
      imageSize: new AMapTool.current.Size(30, 30),
      ...iconConfig
    })
    const marker = new AMapTool.current.Marker({
      title: data.companyName,
      position: new AMapTool.current.LngLat(lng, lat),
      icon,
      zIndex: 99999,
      extData: data,
      offset: new AMapTool.current.Pixel(-30, -30),
      ...markerConfig
    })
    return marker
  }

  useEffect(() => {
    if (companyList?.length && mapRef) {
      mapRef?.clearMap()
      const markers = companyList.map((item) => createParkMaker(item, MapIcon1))
      markers.forEach((marker) => marker.setMap(mapRef))
    } else {
      mapRef?.clearMap()
    }
  }, [companyList, mapRef])

  return (
    <div className="space-map">
      <div id="mapContainer" className="map-container">
        <div className="city-tab-content">
          <ul className="city-tabs-list">
            {cityList.map((item, index) => (
              // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
              <li key={index} className={`city-tabs-item ${activeValue === item.label ? 'is-active' : ''}`} onClick={() => handleCityTabsClick(item)}>
                {item.label}
                {index === cityList.length - 1 ? '' : '/'}
              </li>
            ))}
          </ul>
        </div>
        <AMap plugins={['AMap.DistrictLayer']} optionsFunc={option} mapKey={'c20cfae3e111545b96f372fd73426ee6'}></AMap>
      </div>
    </div>
  )
}

export default memo(SpaceMap)
